package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxx.common.Code;
import com.xxx.common.Result;

import com.xxx.pojo.Home;
import com.xxx.service.FileService;
import com.xxx.service.HomeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/home")
public class HomeController {

    @Autowired
    private HomeService homeService;

    @Autowired
    private FileService fileService;

    @PreAuthorize("hasAnyAuthority('sys:select:home')")
    @GetMapping("/all")
    public Result selectAll(){
        List<Home> list = homeService.list();
        return Result.success("查询成功",list);
    }

    @PreAuthorize("hasAnyAuthority('sys:update:home')")
    @Transactional
    @PutMapping("/update")
    public Result updateHomeImg(@RequestBody Home home){
        if (Objects.isNull(home)){
            return Result.error(Code.USER_ERROR,"修改对象为空");
        }
        System.out.println(home);
        home.setUpdateTime(LocalDateTime.now());
        boolean b = homeService.updateById(home);
        return b?Result.success("修改成功!") : Result.error("修改失败!") ;
    }


    @PreAuthorize("hasAnyAuthority('sys:delete:home')")
    @Transactional
    @DeleteMapping("/delete/{ids}")
    public Result deleteByIdsImg(@PathVariable List<Long> ids){
        boolean b=true;
        for (Long id : ids) {
            Home home = homeService.getById(id);
            boolean b1 = fileService.delImage(home.getImg());
            b = homeService.update(new LambdaUpdateWrapper<Home>().set(Home::getImg, "").eq(Home::getId, id));
        }
        if (!b){
            return Result.error("删除失败!");
        }
        return Result.success("删除成功!");
    }

    @GetMapping("/background")
    public Result selectBackgroundImage(){
        List<Home> list = homeService.list();
        for (Home home : list) {
            if (home.getStatus().getI() == 1){
                home.setImg("");
            }
        }
        return Result.success("查询成功!",list);
    }
}
